<template>
  <div class='container' ref="container">
    <el-card>
      <template #header>
        <span>{{dataId ? '试题修改':'试题录入'}}</span>
      </template>
      <el-form ref="form" :model="subForm" label-width="100px" label-position="left" :rules="rules">
        <el-form-item label="学科" prop="subjectID">
          <el-select  v-model="subForm.subjectID" @change="subjectChange">
            <el-option v-for="item in subjectList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录" prop="catalogID">
          <el-select  v-model="subForm.catalogID" ref="catalogName">
            <el-option v-for="item in catalogList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业" prop="enterpriseID">
          <el-select  v-model="subForm.enterpriseID">
            <el-option v-for="item in companyList" :key="item.id" :label="item.company" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="province">
          <div class="city">
            <el-select v-model="subForm.province" @change="provincesChange">
              <el-option v-for="(item, index) in provincesList" :key="index" :label="item" :value="item"></el-option>
            </el-select>
            <el-select v-model="subForm.city">
              <el-option v-for="(item, index) in citysList" :key="index" :label="item" :value="item"></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="方向" prop="direction">
          <el-select v-model="subForm.direction">
            <el-option v-for="(item, index) in directionList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型" prop="questionType" >
          <el-radio v-model="subForm.questionType" label="1">单选</el-radio>
          <el-radio v-model="subForm.questionType" label="2">多选</el-radio>
          <el-radio v-model="subForm.questionType" label="3">简答</el-radio>
        </el-form-item>
        <el-form-item label="难度" prop="difficulty">
          <el-radio v-model="subForm.difficulty" label="1">简单</el-radio>
          <el-radio v-model="subForm.difficulty" label="2">一般</el-radio>
          <el-radio v-model="subForm.difficulty" label="3">困难</el-radio>
        </el-form-item>
        <el-form-item label="题干" prop="question" class="editor">
          <quill-editor v-model="subForm.question" :options="editorOption"></quill-editor>
        </el-form-item>
        <el-form-item label="选项" v-if="subForm.questionType === '1'">
          <div v-for="item in subForm.options" :key="item.id" class="option">
            <el-radio v-model="radioCode" :label="item.code" @change="radioChange"></el-radio>
            :
            <el-input v-model="item.title"></el-input>
            <el-upload action="">
              <el-button>上传图片</el-button>
            </el-upload>
          </div>
          <el-button type="danger" :disabled="subForm.questionType === '1'">+增加选项与答案</el-button>
        </el-form-item>
        <el-form-item label="选项" v-else-if="subForm.questionType === '2'">
          <div v-for="item in subForm.options" :key="item.id" class="option">
            <el-checkbox v-model="item.isRight" :label="item.code" :checked="item.isRight === 1"></el-checkbox>
            :
            <el-input v-model="item.title"></el-input>
            <el-upload action="">
              <el-button>上传图片</el-button>
            </el-upload>
          </div>
          <el-button type="danger" :disabled="subForm.questionType === '1'" @click="addChoice">+增加选项与答案</el-button>
        </el-form-item>
        <el-form-item label="解析视频">
          <el-input v-model="subForm.videoURL"></el-input>
        </el-form-item>
        <el-form-item label="答案解析" prop="answer" class="editor">
          <quill-editor v-model="subForm.answer" :options="editorOption"></quill-editor>
        </el-form-item>
        <el-form-item label="题目备注">
          <el-input type="textarea" rows="3" v-model="subForm.remarks"></el-input>
        </el-form-item>
        <el-form-item label="试题标签">
          <el-select v-model="subForm.tags" multiple>
            <el-option v-for="item in tagsList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-button type="primary" @click="confirm">{{dataId ? '确认修改': '确认提交'}}</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects'
import { simple as catalogSimple } from '@/api/hmmm/directorys'
import { simple as tagsSimple } from '@/api/hmmm/tags'
import { add as addQuestion, detail as getDetail, update as updateQuestion } from '@/api/hmmm/questions'
import { direction } from '@/api/hmmm/constants'
import { provinces, citys } from '@/api/hmmm/citys'
import { list as getCompanyList } from '@/api/hmmm/companys'

import { quillEditor } from 'vue-quill-editor' // 调用编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import hljs from 'highlight.js'
import 'highlight.js/styles/arta.css'
export default {
  data () {
    return {
      subjectList: [],
      catalogList: [],
      directionList: direction,
      provincesList: provinces(),
      citysList: [],
      companyList: [],
      tagsList: [],
      radioCode: '',
      editorOption: {
        placeholder: '请在这里输入',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote', 'code-block'], // 引用，代码块
            ['image', 'video']
          ],
          syntax: {
            highlight: text => {
              return hljs.highlightAuto(text).value // 这里就是代码高亮需要配置的地方
            }
          }
        }
      },
      subForm: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [ // 选项
          { code: 'A', title: '', img: '', id: '1', isRight: false },
          { code: 'B', title: '', img: '', id: '2', isRight: false },
          { code: 'C', title: '', img: '', id: '3', isRight: false },
          { code: 'D', title: '', img: '', id: '4', isRight: false }
        ],
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      rules: {
        subjectID: [
          { required: true, message: '内容不能为空' }
        ],
        catalogID: [
          { required: true, message: '内容不能为空' }
        ],
        enterpriseID: [
          { required: true, message: '内容不能为空' }
        ],
        province: [
          { required: true, message: '内容不能为空' }
        ],
        direction: [
          { required: true, message: '内容不能为空' }
        ],
        questionType: [
          { required: true, message: '内容不能为空' }
        ],
        difficulty: [
          { required: true, message: '内容不能为空' }
        ],
        question: [
          { required: true, message: '内容不能为空' }
        ],
        answer: [
          { required: true, message: '内容不能为空' }
        ]
      }
    }
  },
  computed: {
    dataId () {
      return this.$route.query.id
    }
  },
  components: {
    quillEditor
  },
  created () {
    if (this.dataId) {
      this.getDetail()
      // this.$forceUpdate()
      this.$nextTick()
      // document.body.scrollTop = document.documentElement.scrollTop = 0
      // console.log('1111')
    }
    this.getSubjectList()
    this.getCompanyList()
  },
  mounted () {
    document.documentElement.scrollTop = 0
    console.log('1111')
  },
  methods: {
    async getSubjectList () {
      const data = await simple()
      // console.log(data)
      this.subjectList = data.data
    },
    subjectChange () {
      // this.subForm.tags = []
    },
    provincesChange () {
      this.citysList = citys(this.subForm.province)
    },
    async getCompanyList () {
      const data = await getCompanyList({ page: 1, pagesize: 1000 })
      // console.log(data)
      this.companyList = data.data.items
      // console.log(this.companyList)
    },
    radioChange () {
      this.subForm.options.forEach(item => {
        if (item.code === this.radioCode) {
          item.isRight = true
        } else {
          item.isRight = false
        }
      })
      // console.log(this.subForm.options)
    },
    async confirm () {
      try {
        await this.$refs.form.validate()
      } catch {
        return
      }
      if (this.dataId) {
        const newTags = this.subForm.tags.join(',')
        await updateQuestion({ id: this.dataId, ...this.subForm, tags: newTags })
        // console.log(res)
      } else {
        const simpleTags = await tagsSimple()
        const newArr = []
        this.subForm.tags.forEach(item => {
          console.log(item, simpleTags.data)
          newArr.push(simpleTags.data.find(v => v.value === item).label)
        })
        this.subForm.tags = newArr.join(',')
        await addQuestion({ ...this.subForm })
        // console.log(data)
      }
      this.$message.success('操作成功')
      this.$router.push('/questions/list')
    },
    addChoice () {
      const length = this.subForm.options.length
      const num = this.subForm.options[length - 1].code.charCodeAt()
      const newCode = String.fromCharCode(+num + 1)
      const newId = Number(this.subForm.options[length - 1].id) + 1
      // console.log(String(newId))
      this.subForm.options.push({
        code: newCode,
        title: '',
        img: '',
        id: String(newId),
        isRight: false
      })
    },
    async getDetail () {
      const data = await getDetail({ id: this.dataId })
      // console.log(data)
      this.subForm = data.data
      this.radioCode = this.subForm.options.find(item => item.isRight === 1).code
      const tagsArr = data.data.tags.split(',')
      this.subForm.tags = tagsArr
      this.subForm.difficulty = String(data.data.difficulty)
      this.subForm.questionType = String(data.data.questionType)
      // console.log(this.subForm.difficulty, this.subForm.questionType)
      // const newCatalog = await catalogSimple()
      // console.log('new', newCatalog)
      // this.subForm.catalogID = newCatalog.data.find(item => item.value === data.data.catalogID).label
    }
  },
  watch: {
    'subForm.questionType': {
      handler () {
        if (!this.dataId) {
          this.radioCode = ''
          this.subForm.options = [
            { code: 'A', title: '', img: '', id: '1', isRight: false },
            { code: 'B', title: '', img: '', id: '2', isRight: false },
            { code: 'C', title: '', img: '', id: '3', isRight: false },
            { code: 'D', title: '', img: '', id: '4', isRight: false }
          ]
        }
      }
    },
    'subForm.subjectID': {
      async handler () {
        if (this.subForm.subjectID) {
          const res = await catalogSimple({ subjectID: this.subForm.subjectID })
          // console.log(res)
          this.catalogList = res.data
          const data = await tagsSimple({ subjectID: this.subForm.subjectID })
          // console.log(data)
          this.tagsList = data.data
        }
      }
    },
    deep: true
  }
}
</script>

<style scoped lang='scss'>
  .el-form{
    width: 500px;
  }
  .el-select{
    width: 100%;
  }
  .city{
    width: 100%;
    display: flex;
  }
  .el-button{
    margin-left: 32px;
  }
  .option{
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 10px;
    ::v-deep{
      .el-radio,
      .el-checkbox{
        margin: 0;
      }
      .el-button{
        line-height: 2;
        margin-left: 5px;
      }
      .el-input{
        margin-left: 5px;
      }
    }
  }
  .editor{
    width: 800px;
    height: 250px;
  }
  .quill-editor {
    height: 200px;
  }
</style>
